<template>
  <div class="main-wrapper">
    <!-- 专业类别筛选 -->
    <!--<div class="content-filterbox">
			<div class="content-filter">
				<div class="content-filtername">专业：</div>
				<div v-for="(item, index) in majorTree" :key="`major${index}`" class="content-filteritem" :class="`${ item.id === currentMajor.id ? 'active' : ''}`" @click="handleMajorChange(item)">{{ item.text }}</div>
			</div>
			<div class="content-filter">
				<div class="content-filtername">分类：</div>
				<div class="content-filteritem" v-show="!loadingData">请选择专业</div>
				<div v-for="(item, index) in currentMajor.children" :key="`type${index}`" class="content-filteritem" :class="`${ item.id === currentType.id ? 'active' : ''}`" @click="currentType = item; simulationResourcePage()">{{ item.text }}</div>
			</div>
		</div>-->
    <!-- 用户咨询 -->
    <div class="fictitious_rightBtnsbox">
      <div class="zxd" v-if="this.$store.state.im.messages.code == 2"></div>
      <div class="zxbox" @click.stop="listshow = !listshow">
        <div class="zx tool">
          <img src="@/images/zixunac.png" alt="" srcset="" class="normal" />
          <img src="@/images/zixunac.png" alt="" srcset="" class="active" />
        </div>
        <div class="zxdes">咨询</div>
      </div>
    </div>
    <!-- 联系人列表 -->
    <div class="listbox beautifulScroll" v-show="listshow">
      <div class="listtile">联系人列表</div>

      <div class="listboxmain beautifulScroll">
        <div
          v-for="item in userlist"
          :key="item.userId"
          class="listitem"
          @click="classroomIdfn(item.userId)"
        >
          <div class="listitemimg">
            <img
              :src="item.iconurl"
              alt=""
              v-img-error="handleImageError"
              v-if="item.avatar"
            />
            <img src="@/images/user_infoicon.png" v-else />
          </div>
          <div
            class="userzxd"
            v-if="messagesfromId.includes(item.userId)"
          ></div>
          <div class="listname">{{ item.name }}</div>
          <div class="listnames">查看</div>
          <div class="xxxtx" v-if="messagesfromId.includes(item.userId)">
            <img src="@/images/xxxtx.png" alt="" />
          </div>
          <!--  -->
        </div>
      </div>
    </div>
    <!-- 用户聊天 -->
    <vimVue
      :classroomId="classroomId"
      v-show="vimshow"
      @closeTalk="closeTalk"
      @classroomIdfns="classroomIdfns"
      class="vim"
    />
    <!-- 搜索栏 -->
    <div class="search-wrapper">
      <el-form :inline="true" :model="params" class="demo-form-inline">
        <el-form-item label="实验名称">
          <el-input v-model="params.name" placeholder="实验名称" clearable />
        </el-form-item>
        <el-form-item label="实验标识">
          <el-input v-model="params.code" placeholder="实验标识" clearable />
        </el-form-item>
        <el-form-item label="组织机构">
          <el-select
            v-model="params.orgId"
            placeholder="请选择组织机构"
            clearable
          >
            <el-option
              v-for="item in depts"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="createLimit"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="simulationResourcePage()"
          ></el-date-picker>
        </el-form-item>
        <el-button type="primary" @click="simulationResourcePage()"
          >查询</el-button
        >
        <el-button @click="createResource()" type="primary">添加实验</el-button>
      </el-form>
    </div>

    <div class="page-wrapper" v-if="resources.length > 0">
      <div class="sy" v-for="item in resources" :key="item.index">
        <div class="syfmimg">
          <!-- <img :src="item.cover" alt="" /> -->
          <el-image :src="item.cover" class="cover-content" fit="cover">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline">图片资源失效</i>
            </div>
          </el-image>
        </div>
        <div class="syname">{{ item.name }}</div>
        <div class="syzzjg">
          <div>组织机构</div>
          <div v-show="item.deptName != null">{{ item.deptName }}</div>
          <div v-show="item.deptName == null">暂无分配</div>
        </div>
        <div class="syupdate">
          <div>最近更新时间</div>
          <div>{{ item.createTime }}</div>
        </div>
        <div class="syments">
          <div class="bjments" @click="showResourceInfo(item.id)">
            <i class="el-icon-edit-outline"></i>
            编辑
          </div>
          <div class="bjments" @click="showResourceDelete(item.id)">
            <i class="el-icon-delete"></i>
            删除
          </div>
          <div class="bjments" @click="showResourceUpdate(item.id)">
            <i class="el-icon-edit"></i>
            更新
          </div>
          <div class="bjments bjmentss" @click="showRecordingFn(true, item.id)">
            <i class="el-icon-tickets"></i>
            记录
          </div>
          <div class="bjments bjmentss">
            <el-tooltip
              :content="item.state == 0 ? '开启' : '关闭'"
              placement="top"
            >
              <el-switch
                :active-value="item.state == 0"
                :inactive-value="item.state == 1"
                @change="showResourceStatus(item)"
              >
              </el-switch
            ></el-tooltip>
          </div>
        </div>
      </div>
      <div style="width: 100%;margin: 15px;text-align: center;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageInfo.current"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total"
        ></el-pagination>
      </div>
    </div>
    <div class="page-wrapper zygxjl zygxjls" v-else>暂无实验资源</div>
    <!-- 仿真实验列表 -->

    <!-- 记录弹窗 -->

    <el-dialog
      :visible.sync="showRecording"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      @close="beforecolse"
      class="jldialog"
    >
      <div class="jlbox">
        <div
          class="jlan"
          :class="updatestep == 1 ? 'jlandt' : ''"
          @click="updatestepFn(1)"
        >
          更新记录
        </div>
        <div
          class="jlan"
          :class="updatestep == 2 ? 'jlandt' : ''"
          @click="updatestepFn(2)"
        >
          反馈记录
        </div>
        <div
          class="jlan"
          :class="updatestep == 3 ? 'jlandt' : ''"
          @click="updatestepFn(3)"
        >
          访问记录
        </div>
      </div>
      <div class="jlnrbox">
        <div v-if="updatestep == 1">
          <resource-update
            ref="resourceRecords"
            :resourceId="resourceUpdateId"
            v-if="resourceUpdateId"
          />
        </div>
        <div v-if="updatestep == 2">
          <resource-back :resourceId="resourceBackId" v-if="resourceBackId" />
        </div>
        <div v-if="updatestep == 3">
          <resource-open
            :resourceId="resourceOpenId"
            v-if="resourceUpdateId"
            ref="resourcebacks"
          />
        </div>
      </div>
    </el-dialog>

    <!-- 新增 编辑 更新 -->
    <el-dialog
      :title="resource.name ? resource.name : '新增虚拟仿真实验'"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :class="updateshow ? 'changeStyles' : 'changeStyle'"
      :key="updateshow"
      v-if="dialogVisible"
    >
      <resource-edit
        ref="edit"
        :resource="resource"
        :isModify="isModify"
        class="dialog-content"
        v-if="!updateshow && dialogVisible"
      />

      <updates
        ref="update"
        class="dialog-content"
        v-if="updateshow && dialogVisible"
        :resource.sync="resource"
        :isModify="isModify"
      />
      <div
        slot="footer"
        :class="updateshow ? 'dialog-footers' : 'dialog-footer'"
      >
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary" @click="submit()" :disabled="dataloading"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import WebsocketHeartbeatJs from '@/utils/websocketIm'
import ResourceEdit from './edit'
import ResourceBack from './back'
import ResourceUpdate from './update'
import ResourceOpen from './open'
import { getInfo } from '@/api/sysUser'
import { getToken } from '@/utils/auth'
import { deptList } from '@/api/sysDept.js'
import {
  simulationState,
  simulationResourcePage,
  getSimulationResource,
  saveSimulationResource,
  updateSimulationResource,
  removeSimulationResource,
  majorTree,
  updateResources,
  getvrExamineRecord
} from '@/api/simulation.js'
import Updates from './updates.vue'
import { userlist } from '@/api/user.js'
import vimVue from '@/components/vim.vue'
export default {
  name: 'simulationResource',
  components: {
    ResourceEdit,
    ResourceBack,
    ResourceUpdate,
    ResourceOpen,
    Updates,
    vimVue
  },
  data() {
    return {
      showRecording: false,
      updateshow: false,
      depts: [],
      params: {}, // 实验查询参数
      createLimit: [], // 实验查询参数时间区间
      resources: [], // 实验资源列表
      pageInfo: {
        limit: 10
      }, // 实验资源列表分页参数
      dialogVisible: false, // 控制编辑模态框状态\
      resource: {
        userList: []
        // major_id: 1,
        // type_id: 1
      }, // 当前操作的实验
      isModify: true, // 当前操作实验是否为编辑模式(初始化后不可改变的值在编辑模式下应禁用修改)
      majorTree: [], // 专业参数树
      currentMajor: {}, // 当前所选专业详情
      currentType: {}, // 当前所选类别详情
      dataloading: false,
      loadingData: false,
      dialogBack: false,
      resourceBackId: '',
      dialogUpdate: false,
      resourceUpdateId: '',
      dialogOpen: false,
      resourceOpenId: '',
      userinfo: {},
      updatestep: 1,
      updatejlid: '',
      userlist: [],
      listshow: false,
      classroomId: '',
      vimshow: false,
      messageList: [],
      messagesfromId: []
    }
  },
  created() {
    // RequestUtils.getInstance().webSocketOperation(this)
    this.simulationResourcePage()
    this.getMajorTree()
    this.getDeptList()
    this.getInfo()
    this.userList()

    this.$store.watch(
      () => this.$store.state.im.messages,
      (newUser, oldUser) => {
        if (newUser.code == 2) {
          console.log('消息来源id', newUser.message.fromId)
          this.messagesfromId.push(newUser.message.fromId)
          const targetIndex = this.userlist.findIndex(
            item => item.userId == newUser.message.fromId
          )

          if (targetIndex !== -1) {
            // 移除原来的位置
            const removedUser = this.userlist.splice(targetIndex, 1)
            // 将该用户信息插入数组开头
            this.userlist.unshift(removedUser[0])
            console.log('更新后的消息列表', this.userlist)
          }
        }
      }
    )
  },
  computed: {
    // ...mapState(['messages'])
  },
  methods: {
    closeTalk() {
      this.vimshow = false
    },
    classroomIdfns(id) {
      const index = this.messagesfromId.indexOf(id)
      if (index !== -1) {
        // 如果 userId 存在于 messagesfromId 数组中，移除它
        this.messagesfromId.splice(index, 1)
      }
    },
    classroomIdfn(id) {
      this.classroomId = id
      this.vimshow = true
      this.classroomIdfns(id)
    },
    userList() {
      userlist().then(async res => {
        this.userlist = res.data
        // console.log('获取消息列表', this.userlist)
      })
    },
    beforecolse() {
      this.updatestep = 1
      this.resourceBackId = null
      console.log('执行了关闭前回调')
      if (this.$refs.resourceRecords) {
        this.$refs.resourceRecords.resourceRecords = []
      }
      if (this.$refs.resourcebacks) {
        this.$refs.resourcebacks.resourcebacks = []
      }
    },
    handleImageError(event) {
      // console.error('图片加载失败:', event)

      // 替换为默认图片
      event.target.src = require('@/images/user_infoicon.png') // 替换为你的默认图片路径
    },
    updatestepFn(i) {
      if (i == 1) {
        this.updatestep = 1
        this.showResourceUpdatejl(this.updatejlid)
      } else if (i == 2) {
        this.updatestep = 2
        this.showResourceBack(this.updatejlid)
      } else if (i == 3) {
        this.updatestep = 3
        this.showResourceOpen(this.updatejlid)
      }
    },
    showRecordingFn(i, id) {
      this.showRecording = i
      this.updatestep = 1
      this.updatejlid = id
      this.showResourceUpdatejl(this.updatejlid)
    },
    getDeptList() {
      deptList({}).then(async res => {
        this.depts = res.children
      })
    },
    getInfo() {
      var token = getToken()
      getInfo().then(res => {
        this.userinfo = res.data
      })
      // 查询数据
      getvrExamineRecord().then(res => {
        console.log('查询考核列表', res)
      })
    },
    /**
     * 分页查询
     */
    simulationResourcePage() {
      if (this.currentType.id == null) {
        this.loadingData = true
      }
      this.params.majorId = this.currentMajor.id
      this.params.typeId = this.currentType.id
      this.params.createStart = this.createLimit ? this.createLimit[0] : null
      this.params.createEnd = this.createLimit ? this.createLimit[1] : null
      this.params.systemType = 'admin'
      simulationResourcePage(Object.assign(this.params, this.pageInfo)).then(
        ({ code, msg, data }) => {
          if (code !== 'OK') {
            this.$message('系统出错, 请联系管理员')
            return
          }
          const { records, current, size, total } = data
          this.resources = records
          this.pageInfo = {
            current,
            total,
            limit: size
          }
          this.loading = false
        }
      )
    },
    /**
     * 删除
     */
    showResourceDelete(resourceId) {
      this.$confirm('是否删除该虚拟仿真实验?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          removeSimulationResource(resourceId).then(({ code, msg, data }) => {
            if (code !== 'OK') {
              this.$message.error(msg)
              return
            }
            this.$message.success('已删除!')
            this.simulationResourcePage()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    /**
     * 新增
     */
    saveResource() {
      // this.resource.deptId = this.resource.orgId
      // this.records.userList = this.resource.contactsInfo

      saveSimulationResource(this.resource).then(({ code, msg, data }) => {
        if (code === 'OK') {
          this.$message.success('已添加')
          this.dialogVisible = false
          this.simulationResourcePage()
        } else if (code === 'INVALID_PARAMETERS') {
          this.$message.error(data)
        } else {
          this.$message.error(msg)
        }
      })
    },
    /**
     * 修改
     */
    async updateResource(i) {
      // console.log('更新内容', this.resource)
      // this.resource.deptId = this.resource.orgId
      // this.records.userList = this.resource.contactsInfo
      // this.resource.userList = this.userList
      if (i) {
        console.log('更新内容', this.resource)
        this.resourcedata = {
          id: this.resource.id,
          attachPrefix: this.resource.attachPrefix,
          url: this.resource.url,
          context: this.resource.context
        }
        updateResources(this.resourcedata).then(({ code, data }) => {
          if (code === 'OK') {
            this.$message.success('已修改')
            this.dialogVisible = false
            this.simulationResourcePage()
          }
        })
      } else {
        updateSimulationResource(this.resource).then(({ code, data }) => {
          if (code === 'OK') {
            this.$message.success('已修改')
            this.dialogVisible = false
            this.simulationResourcePage()
          }
        })
      }
    },
    /**
     * 专业查询参数获取
     */
    getMajorTree() {
      majorTree().then(({ children }) => {
        this.majorTree = children
      })
    },
    handleMajorChange(major) {
      if (this.currentMajor === major) {
        return
      }
      this.currentMajor = major
      this.currentType = {}
      this.simulationResourcePage()
    },
    createResource() {
      this.resource = {
        version: '1.0.0',
        sort: 1,
        state: 0,
        introductionJson: {
          content: ''
        }
      }
      this.isModify = false
      this.openDialog()

      if (this.$refs['edit']) {
        this.$refs['edit'].resetForm()
      }
    },
    showResourceStatus(item) {
      var textInfo = '确认启用实验？'
      var state = '1'
      if (item.state == '1') {
        textInfo = '确认禁用实验?'
        state = '0'
      }
      this.$confirm(textInfo, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          simulationState({
            resourceId: item.id,
            state: state
          }).then(({ code, msg, data }) => {
            if (code !== 'OK') {
              this.$message.error(msg)
              return
            }
            this.$message.success('已修改!')
            this.simulationResourcePage()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    async showResourceInfo(resourceId) {
      const { code, msg, data } = await getSimulationResource(resourceId)
      data.version = data.version || '1.0.0'
      data.introductionJson = JSON.parse(data.introduction)
      this.resource = data
      this.isModify = true

      if (code == 'ok') {
        console.log('执行了查询', code)
        this.resource.userList = this.resource.userId
        console.log('执行了查询', this.resource.userList)
      }

      this.openDialog()

      // if (code == 'ok') {
      //   console.log('执行了查询', code)

      //   // if (this.$refs.edit) {
      //   //   this.$refs.edit.getDepUser()
      //   // }
      // }
      //
      // this.resource.userList = [this.resource.userIdList[0]]
      //
    },
    async showResourceUpdate(resourceId) {
      const { code, msg, data } = await getSimulationResource(resourceId)
      data.version = data.version || '1.0.0'
      data.introductionJson = JSON.parse(data.introduction)
      this.resource = data
      this.isModify = true
      this.openDialogs()
    },
    showResourceUpdatejl(resourceId) {
      this.resourceUpdateId = resourceId
      // this.dialogUpdate = true
    },
    showResourceBack(resourceId) {
      this.resourceBackId = resourceId
      this.dialogBack = true
    },
    showResourceOpen(resourceId) {
      this.resourceOpenId = resourceId
      // this.dialogOpen = true
    },
    openDialogs() {
      if (this.$refs.update) {
        this.$refs.update.initForm()
      }
      this.dialogVisible = true
      this.updateshow = true
    },
    openDialog() {
      this.dialogVisible = true
      this.updateshow = false
      // this.resource.userList = []
      if (this.$refs.edit) {
        this.$refs.edit.initForm()
        this.$refs.edit.getDepUser()
      }
    },
    submit() {
      if (this.updateshow) {
        this.updateResource(true)
        // console.log('更新')
      }
      this.dataloading = true
      setTimeout(() => {
        this.dataloading = false
      }, 1000)
      if (!this.$refs.edit) {
        return
      }
      this.$refs.edit
        .beforeSubmit()
        .then(() => {
          this.isModify
            ? this.updateResource(this.updateshow)
            : this.saveResource()
          this.dialogVisible = false
        })
        .catch(err => {
          console.log(err)
        })
      this.$refs.edit.userList = []
      // this.updateshow = !this.updateshow
    },
    cancel() {
      // 编辑页第一次初始化 || 未锁定
      if (!this.$refs.edit || !this.$refs.edit.isLock) {
        this.dialogVisible = false
        return
      }
      if (this.$refs.edit) {
        this.$refs.edit.deptUser = []
        this.$refs.edit.userList = []
      }
      // 文件上传中提示
      this.$confirm('资源上传中，是否取消上传？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 重设表单
          this.$refs.edit.resetForm()
          // 更改状态框打开状态
          this.dialogVisible = false
          this.$message.success('已取消')
        })
        .catch(() => {})
      this.dialogVisible = false
      // this.updateshow = !this.updateshow
    },
    handleCurrentChange(page) {
      this.pageInfo.current = page
      this.simulationResourcePage()
    },
    handleSizeChange(size) {
      this.pageInfo.limit = size
      this.pageInfo.currnet = 1
      this.simulationResourcePage()
    }
  }
}
</script>
<style>
.zygxjls {
  text-align: center;
  display: flex;
  align-content: center;
  justify-content: center;
}
</style>
